/**
 * @file startup_monitor.cpp
 * @brief 认证服务启动状态监控器 - 监控服务启动过程和状态
 * @author 29108
 * @date 2025/8/2
 * @version 1.0
 *
 * 功能特性:
 * - 启动阶段监控
 * - 组件状态检查
 * - 启动失败诊断
 * - 启动时间统计
 * - 启动日志记录
 */

#include "core_services/auth_service/startup_monitor.h"
#include "common/logger/logger.h"
#include <chrono>
#include <iomanip>
#include <sstream>

namespace core_services {
    namespace auth_service {

        StartupMonitor::StartupMonitor() 
            : current_stage_(StartupStage::INITIALIZING)
            , start_time_(std::chrono::steady_clock::now())
            , stage_start_time_(start_time_) {
        }

        void StartupMonitor::setStage(StartupStage stage, const std::string& description) {
            auto now = std::chrono::steady_clock::now();
            auto stage_duration = std::chrono::duration_cast<std::chrono::milliseconds>(
                now - stage_start_time_).count();

            // 记录上一阶段完成
            if (current_stage_ != StartupStage::INITIALIZING) {
                LOG_INFO("启动阶段完成: " + getStageDescription(current_stage_) + 
                        " (耗时: " + std::to_string(stage_duration) + "ms)");
            }

            // 设置新阶段
            current_stage_ = stage;
            stage_start_time_ = now;
            
            std::string stage_desc = description.empty() ? getStageDescription(stage) : description;
            LOG_INFO("启动阶段开始: " + stage_desc);
        }

        void StartupMonitor::recordError(const std::string& component, const std::string& error) {
            std::lock_guard<std::mutex> lock(errors_mutex_);
            StartupError startup_error;
            startup_error.component = component;
            startup_error.error_message = error;
            startup_error.timestamp = std::chrono::steady_clock::now();
            startup_error.stage = current_stage_;
            errors_.push_back(startup_error);

            LOG_ERROR("启动错误 [" + component + "]: " + error);
        }

        void StartupMonitor::recordSuccess(const std::string& component, const std::string& message) {
            auto now = std::chrono::steady_clock::now();
            auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(
                now - stage_start_time_).count();
                
            LOG_INFO("组件启动成功 [" + component + "]: " + message + 
                    " (耗时: " + std::to_string(duration) + "ms)");
        }

        bool StartupMonitor::hasErrors() const {
            std::lock_guard<std::mutex> lock(errors_mutex_);
            return !errors_.empty();
        }

        std::vector<StartupError> StartupMonitor::getErrors() const {
            std::lock_guard<std::mutex> lock(errors_mutex_);
            return errors_;
        }

        std::chrono::milliseconds StartupMonitor::getTotalStartupTime() const {
            auto now = std::chrono::steady_clock::now();
            return std::chrono::duration_cast<std::chrono::milliseconds>(now - start_time_);
        }

        std::chrono::milliseconds StartupMonitor::getCurrentStageTime() const {
            auto now = std::chrono::steady_clock::now();
            return std::chrono::duration_cast<std::chrono::milliseconds>(now - stage_start_time_);
        }

        void StartupMonitor::printSummary() const {
            auto total_time = getTotalStartupTime();
            
            LOG_INFO("=== 启动监控摘要 ===");
            LOG_INFO("总启动时间: " + std::to_string(total_time.count()) + "ms");
            LOG_INFO("当前阶段: " + getStageDescription(current_stage_));
            
            std::lock_guard<std::mutex> lock(errors_mutex_);
            if (errors_.empty()) {
                LOG_INFO("启动过程无错误");
            } else {
                LOG_WARNING("启动过程中发现 " + std::to_string(errors_.size()) + " 个错误:");
                for (const auto& error : errors_) {
                    LOG_WARNING("  - [" + error.component + "] " + error.error_message);
                }
            }
        }

        std::string StartupMonitor::getStageDescription(StartupStage stage) const {
            switch (stage) {
                case StartupStage::INITIALIZING:
                    return "初始化";
                case StartupStage::LOADING_CONFIG:
                    return "加载配置";
                case StartupStage::INITIALIZING_LOGGING:
                    return "初始化日志系统";
                case StartupStage::CHECKING_DEPENDENCIES:
                    return "检查依赖";
                case StartupStage::INITIALIZING_DATABASE:
                    return "初始化数据库";
                case StartupStage::INITIALIZING_COMPONENTS:
                    return "初始化业务组件";
                case StartupStage::STARTING_HTTP_SERVER:
                    return "启动HTTP服务器";
                case StartupStage::STARTING_KAFKA:
                    return "启动Kafka组件";
                case StartupStage::REGISTERING_SERVICES:
                    return "注册服务";
                case StartupStage::STARTING_BACKGROUND_TASKS:
                    return "启动后台任务";
                case StartupStage::COMPLETED:
                    return "启动完成";
                case StartupStage::FAILED:
                    return "启动失败";
                default:
                    return "未知阶段";
            }
        }

        // 全局启动监控器实例
        static std::unique_ptr<StartupMonitor> g_startup_monitor = nullptr;

        StartupMonitor& getStartupMonitor() {
            if (!g_startup_monitor) {
                g_startup_monitor = std::make_unique<StartupMonitor>();
            }
            return *g_startup_monitor;
        }

        void resetStartupMonitor() {
            g_startup_monitor.reset();
        }

    } // namespace auth_service
} // namespace core_services
